//
//  TIMElemBaseTableViewCell.m
//  TIMChat
//
//  Created by AlexiChen on 16/3/8.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "TIMElemBaseTableViewCell.h"
#import "UIView+Layout.h"
#import "NSDate+Ext.h"

@implementation TIMElemBaseTableViewCell

- (void)dealloc
{
    [_msgKVO unobserveAll];
    //    DebugLog(@"[%@] relase", [self class]);
}

+ (UIFont *)defaultNameFont
{
    return kIMASmallTextFont;
}
+ (UIFont *)defaultTextFont
{
    return kIMAMiddleTextFont;
}

- (BOOL)canBecomeFirstResponder
{
    return [self canShowMenu];
}

- (BOOL)canShowMenu
{
    return YES;
}

- (BOOL)canShowMenuOnTouchOf:(UIGestureRecognizer *)ges
{
    CGPoint p = [ges locationInView:_contentBack];
    BOOL contain = CGRectContainsPoint(_contentBack.bounds, p);
    return contain;
}

- (instancetype)initWithC2CReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier])
    {
        self.contentView.backgroundColor = kClearColor;
        self.backgroundColor = kClearColor;
        _cellStyle = TIMElemCell_C2C;
        [self addC2CCellViews];
        
    }
    return self;
}
- (instancetype)initWithGroupReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super init])
    {
        self.contentView.backgroundColor = kClearColor;
        self.backgroundColor = kClearColor;
        _cellStyle = TIMElemCell_Group;
        [self addGroupCellViews];
        
    }
    return self;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    _pickedViewRef.hidden = !editing;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self relayoutFrameOfSubViews];
}

- (void)relayoutFrameOfSubViews
{
    //    switch (_cellStyle)
    //    {
    //        case TIMElemCell_C2C:
    //        {
    [self relayoutC2CCellViews];
    //        }
    //            break;
    //        case TIMElemCell_Group:
    //        {
    //            [self relayoutGroupCellViews];
    //        }
    //            break;
    //        default:
    //            break;
    //    }
}


- (void)addC2CCellViews
{
    
    _timeSender = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    _timeSender.textColor = kLightGrayColor;
    _timeSender.font = [TIMElemBaseTableViewCell defaultNameFont];
    _timeSender.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:_timeSender];
    
    _name = [[UILabel alloc] init];
    _name.textColor = kLightGrayColor;
    _name.font = [TIMElemBaseTableViewCell defaultNameFont];
    [self.contentView addSubview:_name];

    _icon = [[UIImageView alloc] init];
    _icon.layer.cornerRadius = 22;
    _icon.layer.masksToBounds = YES;
    _icon.userInteractionEnabled = YES;
    [self.contentView addSubview:_icon];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleIcon:)];
    [_icon addGestureRecognizer:tap];
    
    _contentBack = [[UIImageView alloc] init];
    _contentBack.userInteractionEnabled = YES;
    [self.contentView addSubview:_contentBack];
    _elemContentRef = [self addElemContent];
    if (_elemContentRef)
    {
        [_contentBack addSubview:_elemContentRef];
    }
    
    
    _sendingTipRef = [self addSendingTips];
    if (_sendingTipRef)
    {
        [self.contentView addSubview:_sendingTipRef];
    }
    
    _pickedViewRef = [self addPickedView];
    if (_pickedViewRef)
    {
        _pickedViewRef.hidden = YES;
        [self.contentView addSubview:_sendingTipRef];
    }
    
}
- (void)handleIcon:(UITapGestureRecognizer *)tap {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"tapMessageAvatar" object:_msg];
    if ([_msg isMineMsg])
    {
        UIViewController *viewController = [HelpTool viewControllerOfView:self];

//        PersonVController *vc = [[PersonVController alloc] init];
        
//        BMHPersonalPageVController *vc = [[BMHPersonalPageVController alloc]init];
//
//        NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:BMHUserId];
//        NSLog(@"mmmuhead === %@", self.useID );
//
//        vc.isSelf = YES;
//        vc.userId = userId;
//        [viewController.navigationController pushViewController:vc animated:YES];

    }
    else
    {
        //        user = [_msg getSender];
//        [_icon sd_setImageWithURL:[NSURL URLWithString:imagArr] placeholderImage:kDefaultUserIcon];
        UIViewController *viewController = [HelpTool viewControllerOfView:self];
        if ([_msg isGroupMsg]) {
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"9", @"type",[_msg getSender].userId,@"userid",nil];
            _icon.userInteractionEnabled = NO;
            [BMHHTTPSession GET:@"MobileInterface/group/GroupInfo.ashx" paraments:dic success:^(id  _Nullable JSON) {
                _icon.userInteractionEnabled = YES;
                NSLog(@"mmmuhead2 === %@", JSON );
                NSString * dataState = [NSString stringWithFormat:@"%@",JSON[@"result"][@"errcode"]];

                if ([dataState isEqualToString:@"1"]) {
//                    BMHPersonalPageVController *vc = [[BMHPersonalPageVController alloc]init];
//                    vc.isCTC = NO;
//
//                    vc.isSelf = NO;
//                    vc.userId = [NSString stringWithFormat:@"%@",JSON[@"result"][@"bmhId"]];
//                    [viewController.navigationController pushViewController:vc animated:YES];

                }
            } failure:^(NSError * _Nullable error) {
                _icon.userInteractionEnabled = YES;

            }];
            

        }else{
//            PersonVController *vc = [[PersonVController alloc] init];
//            BMHPersonalPageVController *vc = [[BMHPersonalPageVController alloc]init];
//
//            NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"chatBmhUserID"];
//            vc.isSelf = NO;
//            vc.userId = userId;
//            vc.isCTC = YES;
//            [viewController.navigationController pushViewController:vc animated:YES];

        }

    }

}
// 只创建，外部统一添加
- (UIView *)addElemContent
{
    return nil;
}


// 只创建，外部统一添加
- (UIView<TIMElemSendingAbleView> *)addSendingTips
{
    return nil;
}

// 只创建，外部统一添加
- (UIView *)addPickedView
{
    return nil;
}


- (void)addGroupCellViews
{
    [self addC2CCellViews];
    
    _remarkTip = [[UILabel alloc] init];
    _remarkTip.textColor = kLightGrayColor;
    _remarkTip.font = [TIMElemBaseTableViewCell defaultNameFont];
    [self.contentView addSubview:_remarkTip];
}
//上下左右
- (void)relayoutC2CCellViews
{
    CGRect rect = self.contentView.bounds;
    NSInteger hor = [_msg horMargin];
    NSInteger ver = kDefaultMargin/2;
//我的消息
    if ([_msg isMineMsg])
    {
        if (self.isEditing)
        {
            if (_pickedViewRef)
            {
                [_pickedViewRef sizeWith:CGSizeMake([_msg pickedViewWidth], rect.size.height)];
                [_pickedViewRef alignParentLeftWithMargin:hor];
                [_pickedViewRef relayoutFrameOfSubViews];
            }
        }

        [_icon sizeWith:[_msg userIconSize]];
        [_icon alignParentRightWithMargin:14];
        [_icon alignParentTopWithMargin:ver + 30];
        if ([_msg isGroupMsg]) {
            [_name sizeWith:CGSizeMake(100, 12)];
            [_name layoutToLeftOf:_icon margin:15];
            [_name alignParentTopWithMargin:ver + 20];
        }

        CGSize contentBackSize = [_msg contentBackSizeInWidth:rect.size.width];
        CGSize contentBackSize2 =  CGSizeMake(contentBackSize.width, contentBackSize.height - 30);
        [_contentBack sizeWith:contentBackSize2];
        [_contentBack layoutToLeftOf:_icon margin:hor];
        if ([_msg isGroupMsg]) {
            [_contentBack alignParentTopWithMargin:ver + 35];
            
        }else {
            [_contentBack alignParentTopWithMargin:ver + 35];
            
        }
        
        //布局我的消息
        UIEdgeInsets inset = [_msg contentBackInset];
        contentBackSize.width -= inset.left + inset.right;
        contentBackSize.height -= inset.top + inset.bottom;
        
        if (_elemContentRef)
        {
            [_elemContentRef sizeWith:contentBackSize];
            [_elemContentRef alignParentLeftWithMargin:inset.left];
            [_elemContentRef alignParentTopWithMargin:2];
            [_elemContentRef relayoutFrameOfSubViews];
        }
        
        if (_sendingTipRef)
        {
            NSInteger width = [_msg sendingTipWidth];
            [_sendingTipRef sizeWith:CGSizeMake(width, rect.size.height)];
            [_sendingTipRef layoutToLeftOf:_contentBack margin:hor];
            [_sendingTipRef relayoutFrameOfSubViews];
        }
    }
//对方消息
    else
    {
        // 对方的C2C消息
        
        [_icon sizeWith:[_msg userIconSize]];
        [_icon alignParentTopWithMargin:ver + 30];
        if ([_msg isGroupMsg]) {
            [_name sizeWith:CGSizeMake(100, 12)];
            [_name layoutToRightOf:_icon margin:hor + 10];
            [_name alignParentTopWithMargin:ver + 30];

        }

        if (_pickedViewRef && !_pickedViewRef.hidden)
        {
            [_pickedViewRef sizeWith:CGSizeMake([_msg pickedViewWidth], rect.size.height)];
            [_pickedViewRef alignParentLeftWithMargin:14];
            [_pickedViewRef relayoutFrameOfSubViews];
            
            [_icon layoutToRightOf:_pickedViewRef margin:hor];
        }
        else
        {
            [_icon alignParentLeftWithMargin:hor];
        }
        
        CGSize contentBackSize = [_msg contentBackSizeInWidth:rect.size.width];
        CGSize contentBackSize2 =  CGSizeMake(contentBackSize.width, contentBackSize.height - 30);
        [_contentBack sizeWith:contentBackSize2];
        [_contentBack layoutToRightOf:_icon margin:hor];
        if ([_msg isGroupMsg]) {
            [_contentBack alignParentTopWithMargin:ver + 45];

        }else {
            [_contentBack alignParentTopWithMargin:ver + 35];

        }
        
        //布局对方消息
        UIEdgeInsets inset = [_msg contentBackInset];
        contentBackSize.width -= inset.left + inset.right;
        contentBackSize.height -= inset.top + inset.bottom;
        
        if (_elemContentRef)
        {
            [_elemContentRef sizeWith:contentBackSize];
            [_elemContentRef alignParentLeftWithMargin:inset.left];
            [_elemContentRef alignParentTopWithMargin:2];
            [_elemContentRef relayoutFrameOfSubViews];
        }
        
        if (_sendingTipRef)
        {
            //            _sendingTipRef.hidden = YES;
            NSInteger width = [_msg sendingTipWidth];
            [_sendingTipRef sizeWith:CGSizeMake(width, rect.size.height)];
            [_sendingTipRef layoutToRightOf:_contentBack margin:hor];
            [_sendingTipRef relayoutFrameOfSubViews];
        }
        
    }
}
- (void)relayoutGroupCellViews
{
    CGRect rect = self.contentView.bounds;
    NSInteger hor = [_msg horMargin];
    NSInteger ver = kDefaultMargin/2;
    if ([_msg isMineMsg])
    {
        // 与C2C消息一致
        [self relayoutC2CCellViews];
    }
    else
    {
        // 对方的Group消息
        [_icon sizeWith:[_msg userIconSize]];
        [_icon alignParentTopWithMargin:ver];
        
        if (_pickedViewRef && !_pickedViewRef.hidden)
        {
            [_pickedViewRef sizeWith:CGSizeMake([_msg pickedViewWidth], rect.size.height)];
            [_pickedViewRef alignParentLeftWithMargin:hor];
            [_pickedViewRef relayoutFrameOfSubViews];
            
            [_icon layoutToRightOf:_pickedViewRef margin:hor];
        }
        else
        {
            [_icon alignParentLeftWithMargin:14];
        }
        
        [_remarkTip sizeWith:CGSizeMake(rect.size.width, [_msg groupMsgTipHeight])];
        [_remarkTip alignTop:_icon];
        [_remarkTip layoutToRightOf:_icon margin:hor];
        [_remarkTip scaleToParentRightWithMargin:hor];
        
        CGSize contentBackSize = [_msg contentBackSizeInWidth:rect.size.width];
        [_contentBack sizeWith:contentBackSize];
        [_contentBack layoutToRightOf:_icon margin:hor];
        [_contentBack layoutBelow:_remarkTip];
        [_contentBack alignParentBottomWithMargin:ver];
        
        
        UIEdgeInsets inset = [_msg contentBackInset];
        contentBackSize.width -= inset.left + inset.right;
        contentBackSize.height -= inset.top + inset.bottom;
        
        if (_elemContentRef)
        {
            [_elemContentRef sizeWith:contentBackSize];
            [_elemContentRef alignParentLeftWithMargin:inset.left];
            [_elemContentRef alignParentTopWithMargin:2];
            [_elemContentRef relayoutFrameOfSubViews];
        }
        
        if (_sendingTipRef)
        {
            _sendingTipRef.hidden = YES;
            NSInteger width = [_msg sendingTipWidth];
            [_sendingTipRef sizeWith:CGSizeMake(width, rect.size.height)];
            [_sendingTipRef layoutToRightOf:_contentBack margin:hor];
            [_sendingTipRef relayoutFrameOfSubViews];
        }
        
    }
}

- (void)configKVO
{
    [_msgKVO unobserveAll];
    
    if ([_msg isMineMsg])
    {
        __weak TIMElemBaseTableViewCell *ws = self;
        if (!_msgKVO)
        {
            _msgKVO = [FBKVOController controllerWithObserver:self];
        }
        [_msgKVO observe:_msg keyPath:@"status" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
            [ws configSendingTips];
        }];
    }
    else
    {
        _msgKVO = nil;
    }
    
    
}

- (void)configWith:(IMAMsg *)msg withImage:(NSString *)imagArr withUserId:(NSString *)userID withIndexPath:(NSIndexPath *)indexPath user:(IMAUser *)userinfo
{
    _msg = msg;
    if ([msg.msg isKindOfClass:[TIMCustomElem class]]) {
        TIMCustomElem *elem = (TIMCustomElem *)[_msg.msg getElem:0];
        NSString *dataStr = [[NSString alloc] initWithData:elem.data encoding:NSUTF8StringEncoding];
        NSLog(@"收费视频xss === %@", dataStr);

    }
    self.indexPath = indexPath;
    [self configKVO];
    self.useID = userID;
    IMAUser *user = nil;
    if ([_msg isMineMsg])
    {
        user = [IMAPlatformxl sharedInstance].host;
        NSString *myHead = [[XLAccountManager shareInstance] model].HeadImg;
        [_icon sd_setImageWithURL:[NSURL URLWithString:myHead] placeholderImage:kDefaultUserIcon];
        if ([_msg isGroupMsg]){
            IMAGroup *user = (IMAGroup *)userinfo;

            _name.text =[user selfNamecard].length > 0 ? [user selfNamecard] : [[NSUserDefaults standardUserDefaults] objectForKey:UserNick] ;
            //        _name.backgroundColor = [UIColor redColor];
            _name.textAlignment = NSTextAlignmentRight;

        }
    }
    else
    {
        //        user = [_msg getSender];
        if ([_msg isC2CMsg]) {
            [_icon sd_setImageWithURL:[NSURL URLWithString:imagArr] placeholderImage:kDefaultUserIcon];

        }else  if ([_msg isGroupMsg]){
                    [_icon sd_setImageWithURL:[NSURL URLWithString:[_msg getSender].icon] placeholderImage:kDefaultUserIcon];

            _name.text = [_msg getSender].nickName;
        }else {
            [_icon sd_setImageWithURL:[NSURL URLWithString:imagArr] placeholderImage:kDefaultUserIcon];
 
        }
        

    }
    NSLog(@"imagArrimagArr === %@", imagArr);
    
    //    [_icon sd_setImageWithURL:[NSURL URLWithString:@"https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/6f061d950a7b020872401d0d60d9f2d3562cc854.jpg"] forState:UIControlStateNormal placeholderImage:kDefaultUserIcon];
    
    if (_remarkTip)
    {
        _remarkTip.hidden = !([_msg isGroupMsg] && ![_msg isMineMsg]);
        _remarkTip.font = [_msg tipFont];
        _remarkTip.textColor = [_msg tipTextColor];
        _remarkTip.text = [user showTitle];
    }
    
    
    NSDate *date = [msg.msg timestamp];
    
    _timeSender.text = [date shortTimeDescriptionOfDate];
    
    [self configContent];
    
    if (_pickedViewRef)
    {
        [_pickedViewRef setSelected:_msg.isPicked];
    }
    if (_elemContentRef)
    {
        [self configElemContent];
    }
    
    if (_sendingTipRef)
    {
        [self configSendingTips];
    }
    
}

- (void)configContent
{
    
}

- (void)configElemContent
{
    
}
- (void)configSendingTips
{
    _sendingTipRef.hidden = ![_msg isMineMsg];
}



- (void)showMenu
{
    NSArray *showMenus = [self showMenuItems];
    if (showMenus.count)
    {
        [self becomeFirstResponder];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setMenuItems:showMenus];
        [menu update];
        [menu setTargetRect:_contentBack.frame inView:self.contentView];
        [menu setMenuVisible:YES animated:YES];
    }
    
}
- (void)deletIndexPath:(NSIndexPath *)indexPath {
    [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_DeleteNotification object:_msg];
    
}
- (NSArray *)showMenuItems
{
    
    NSMutableArray *array = [NSMutableArray array];
    
    UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteItem:)];
    [array addObject:deleteItem];
    TIMElem *elem = [_msg.msg getElem:0];
    
    if ([elem isKindOfClass:[TIMTextElem class]]) {
        UIMenuItem *deleteItem1 = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(deleteItem1:)];
        [array addObject:deleteItem1];

    }else {
        
    }
    if (_msg.status == EIMAMsg_SendFail)
    {
        UIMenuItem *resendItem = [[UIMenuItem alloc] initWithTitle:@"重发" action:@selector(resendItem:)];
        [array addObject:resendItem];
    }
    
    return array;
    
}

- (void)deleteItem:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_DeleteNotification object:_msg];
}
- (void)deleteItem1:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"fuzhi" object:_msg];
}

- (void)resendItem:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_ResendNotification object:_msg];
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can;
    TIMElem *elem = [_msg.msg getElem:0];
    
  if ([elem isKindOfClass:[TIMTextElem class]]) {
        can = ((action == @selector(deleteItem:)) || (action == @selector(resendItem:)) || (action == @selector(deleteItem1:)));
 
  }else {
      can = ((action == @selector(deleteItem:)) || (action == @selector(resendItem:)));

  }
    

    return can;
}

@end
